/*
 * @Author: wangtao
 * @Date: 2021-02-18 11:21:01
 * @LastEditors: zeki mini
 * @LastEditTime: 2021-04-23 01:59:03
 * @Description: file content
 */
import React from 'react';
import {
  View,
  StyleSheet,
  Image,
  Text,
  SafeAreaView,
  DeviceEventEmitter,
} from 'react-native';
import {
  leftBack,
  iconHomeGoldInsurance,
  iconHomeGrayInsurance,
} from '@/images';
import {
  msg,
  _,
  cache,
} from '@/common';
import {
  mainBgColorLightGray,
  screenWidth,
  px2dp,
} from '@/styles';
import AsyncStorage from '@react-native-community/async-storage';
import homeApi from '@/api/home';
import api from '@/api';
import RechargeHeader from '../../../components/RechargeHeader';
import XmSwiper from '../../../components/XmSwiper';
import GoodsDefaultPic from '../../../components/LoadingDefaultPic';
import MainMiddleMenu from './compoonents/main-middle-menu';
import MainListHeader from './compoonents/main-list-header';
import ArticleCell from './compoonents/article-cell';
import XmList from '../../../components/XmList';
import EmptyPage from '../../../components/EmptyPage';

export default class InsuranceMain extends React.Component {
  static navigationOptions = () => ({
    title: '首页',
    tabBarIcon: ({ focused }) => (
      <Image
        source={focused ? iconHomeGoldInsurance : iconHomeGrayInsurance}
        style={{ width: 24, height: 24 }}
      />
    ),
  });

  constructor(props) {
    super(props);
    this.state = {
      bannerArr: [], // banner
      articleList: [], //
      isLoading: false,
      showFoot: 1,
    };
  }

  componentDidMount() {
    // this.getCurrentCompany();
    this.loadData();
    // 点击文章详情回来
    this.subscription = DeviceEventEmitter.addListener('insureDetailBack', () => {
      this.setState(
        {
          isLoading: true,
          pageNo: 1,
          articleList: [],
        },
        () => {
          this.partLoadTjData('dropdown');
        },
      );
    });
  }

  componentWillUnmount() {
    this.subscription.remove();
  }

  render() {
    const { bannerArr, articleList, isLoading, showFoot } = this.state;
    const renderItem = ({ item, index }) => {
      return (
        <>
          <ArticleCell
            key={index}
            source={item}
            type={item.cateName || xmType}
            onPress={this.jumpDetail}
          />
          {index === articleList.length - 1 && (
            <View style={styles.footerBox}>
              <View style={styles.leftLines} />
              <Text style={styles.footerText}>
                没有更多啦
              </Text>
              <View style={styles.rightLines} />
            </View>
          )}
        </>
      );
    };
    return (
      <SafeAreaView style={{ flex: 1 }}>
        <View style={{ flex: 1 }}>
          <RechargeHeader
            leftBackStyle={{ backgroundColor: 'rgba(0,0,0,0.1)' }}
            leftBackIcon={leftBack}
            leftTitle='联盟保险机构'
          />
          <XmList
            sources={articleList}
            renderItem={renderItem}
            showVerticalScroll={false}
            ListHeaderComponent={(
              <View>
                <View style={styles.swiperWrap}>
                  {bannerArr && bannerArr.length > 0 ? (
                    <XmSwiper
                      imageData={bannerArr}
                      borderRadius={{ borderRadius: px2dp(6) * 2 }}
                      showDot
                      duration={3}
                      mgWidth={screenWidth - px2dp(32) * 2}
                      clickImage={(imgsItem) => this.getJFGL(imgsItem)}
                      resizeMode='cover'
                      isAuto={false}
                    />
                  ) : (
                    <GoodsDefaultPic style={{ borderRadius: px2dp(6) * 2 }} />
                  )}
                </View>
                <MainMiddleMenu onClickAction={(res) => { this.midListViewActions(res); }} />
                <MainListHeader onClickAction={() => {
                  msg.emit('router: goToNext', {
                    routeName: 'InsuranceArticleList',
                  });
                }}
                />
              </View>
            )}
            isLoading={isLoading}
            onDropdownRefresh={() => this.loadData()}
            singleKey={(item, index) => index.toString()}
            showFoot={showFoot}
            noText='暂无头条'
            customEmptyView={<EmptyPage style={{ marginTop: px2dp(0) }} noText='暂无头条' />}
          />
        </View>
      </SafeAreaView>
    );
  }

  // 获取当前法人
  getCurrentCompany = () => {
    api.insurance.getCurrentCompany().then((res) => {
      if (res.data) {
        AsyncStorage.setItem(
          cache.CURRENT_LEGAL_INSURANCE,
          JSON.stringify(res.data),
        );
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  };

  midListViewActions = (tag) => {
    let routeName = '';
    switch (tag) {
    case 1:
      // 保单管家
      routeName = 'InsuranceListMy';
      break;
    case 2:
      // 一键申请
      routeName = 'InsuranceApply';
      break;
    case 3:
      // 我的申请
      routeName = 'InsuranceApplyListMy';
      break;
    default:
      break;
    }
    msg.emit('router: goToNext', {
      routeName: routeName,
      routerFrom: 'InsuranceMain',
    });
  }

  // 加载固定条数头条
  loadData() {
    this.setState(
      {
        isLoading: true,
        pageNo: 1,
        articleList: [],
      },
      () => {
        this._getHomeBanner();
        this.partLoadTjData('dropdown');
      },
    );
  }

  partLoadTjData = (type) => {
    const myMallParams = {
      appSystem: '缘多新联盟',
      code: 'insuranceList',
      pageNo: 1,
      pageSize: 6
    };

    homeApi.pageDefHomeContentInfo(myMallParams).then(res => {
      let { articleList, pageNo, pageSize } = this.state;
      const newList = res.data.result;
      if (res.success) {
        if (res.data.total === 0) {
          this.setState({
            isLoading: false,
            showFoot: 0
          });
          return;
        }

        if (res.data.result.length <= 0) {
          this.setState({
            isLoading: false,
            showFoot: 1
          });
          return;
        }

        if (type === 'dropdown') {
          this.setState({ isLoading: false });
          articleList = newList.concat(articleList);
        } else if (type === 'pullMore') {
          articleList = articleList.concat(newList);
        }

        this.setState({
          pageNo: pageNo + 1,
          articleList
        });
        if (res.data.result.length <= pageSize) {
          this.setState({
            isLoading: false,
            showFoot: 1
          });
        }
      } else {
        this.setState({
          isLoading: false,
          showFoot: 0
        });
        msg.emit('app:tip', { text: '获取失败' });
      }
    }).catch(err => {
      console.log(err);
      this.setState({
        isLoading: false,
        showFoot: 0
      });
    });
  }

  _getHomeBanner() {
    this.setState({ bannerArr: [] });
    const bannerParams = {
      code: 'insuranceBanner'
    };
    homeApi.getDefContentInfoListByCode(bannerParams).then(res => {
      if (res.success) {
        const bannerPic = res.data;
        let bannerArr = [];
        if (bannerPic && bannerPic.length > 0) {
          bannerArr = bannerPic.map((item) => {
            item.icon = item.imageId;
            return item;
          });
        }
        this.setState({
          bannerArr
        });
      }
    });
  }

  getArticleList() {
    this.setState({
      isLoading: true,
      pageNo: 1,
      articleList: []
    }, () => {
      const { pageNo, pageSize, cateId } = this.state;
      const params = {
        cateId,
        pageNo,
        pageSize,
      };
      homeApi.pageDefContentInfo(params).then(res => {
        if (res.success) {
          this.setState({ articleList: res.data.result });
        }
      });
    });
  }

  jumpDetail = (item) => {
    msg.emit('router: goToNext', {
      routeName: 'InsuranceArticleDetail',
      item
    });
  }

  getJFGL = (imgsItem) => {
    const item = {
      contentId: imgsItem.contentId,
      type: '推荐'
    };
    msg.emit('router: goToNext', {
      routeName: 'InsuranceArticleDetail',
      item
    });
  }
}

const styles = StyleSheet.create({
  container: {
    width: screenWidth,
    height: '100%',
    alignItems: 'center',
    backgroundColor: mainBgColorLightGray,
  },
  swiperWrap: {
    height: screenWidth * 0.36,
    marginLeft: px2dp(16) * 2,
    marginRight: px2dp(16) * 2,
    marginTop: px2dp(12) * 2,
    borderRadius: px2dp(6) * 2,
  },
  footerBox: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: px2dp(32),
    marginBottom: px2dp(64)
  },
  leftLines: {
    width: px2dp(100),
    height: px2dp(1),
    backgroundColor: '#E6E6E5'
  },
  rightLines: {
    width: px2dp(100),
    height: px2dp(1),
    backgroundColor: '#E6E6E5'
  },
  footerText: {
    color: '#CDCCCB',
    fontSize: px2dp(24),
    marginHorizontal: px2dp(16)
  }
});
